using System;
using QAssetBundle;
using UnityEngine;
using QFramework;
using Random = UnityEngine.Random;

namespace XCZProject
{
	/// <summary>
	/// 篮球技能，控制篮球的移动，碰撞等
	/// </summary>
	public partial class Ball : ViewController
	{
		//public BindableProperty<bool> SuperBasketBall = new BindableProperty<bool>(true);
		void Start()
		{
			// Code Here
			// 篮球的移动
			SelfRigibody2D.velocity =
				new Vector2(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f)) * //随机方向
				Random.Range(Global.BasketBallSpeed.Value - 2, Global.BasketBallSpeed.Value + 2);//随机速度

			Global.SuperBasketBall.RegisterWithInitValue(unlocked =>
			{
				if (unlocked)
				{
					this.LocalScale(2);
				}
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
			
			// 篮球的碰撞事件，下面的OnCollisionEnter2D是篮球碰撞摄像机四周反弹的事件，这个才是碰撞敌人的事件
			HurtBox.OnTriggerEnter2DEvent(collider =>
			{
				var hurtBox = collider.GetComponent<HurtBox>();
				if (hurtBox)
				{
					// 如果碰撞的是敌人，就调用敌人的受伤方法
					if (hurtBox.Owner.CompareTag("Enemy"))
					{
						//hurtBox.Owner.GetComponent<IEnemy>().Hurt(Global.BasketBallDamage.Value);
						
						var damageTimes = Global.SuperBasketBall.Value ? Random.Range(2,3+1) : 1;
						// 伤害计算
						DamageSystem.CalculateDamage(Global.BasketBallDamage.Value*damageTimes,
							hurtBox.Owner.GetComponent<IEnemy>());
										
						// 有一定概率触发击退效果
						if (Random.Range(0,1.0f)<0.5f&&collider&&collider.attachedRigidbody&&Player.Default)
						{
							// 把敌人的距离设置为击退一定距离的方向
							collider.attachedRigidbody.velocity =
								collider.NormalizedDirection2DFrom(this) * 5 +
								collider.NormalizedDirection2DFrom(Player.Default) * 10;
						}
					}
				}
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
		}

		private void OnCollisionEnter2D(Collision2D other)
		{
			
			var normal = other.GetContact(0).normal;//获取碰撞的法线

			//根据法线的方向来设置速度
			if (normal.x>normal.y)
			{
				//如果法线的x大于y，说明是左右碰撞，那么就设置y方向的速度
				SelfRigibody2D.velocity=new Vector2(SelfRigibody2D.velocity.x,
					Mathf.Sign(SelfRigibody2D.velocity.y)*Random.Range(0.5f,1.5f)*
					Random.Range(Global.BasketBallSpeed.Value-2,Global.BasketBallSpeed.Value+2));
				SelfRigibody2D.angularVelocity = Random.Range(-360, 360);//设置角速度
			}
			else
			{
				var rb = SelfRigibody2D;
				rb.velocity=new Vector2(
					Mathf.Sign(SelfRigibody2D.velocity.x)*Random.Range(0.5f,1.5f)*
					Random.Range(Global.BasketBallSpeed.Value-2,Global.BasketBallSpeed.Value+2),
					rb.velocity.y);
				rb.angularVelocity = Random.Range(-360, 360);//设置角速度
			}

			// 播放音效
			AudioKit.PlaySound(Sfx.BALL);
		}
	}
}
